package com.example.sen.jxdemo;

import android.Manifest;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Browser;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.jxccp.im.callback.JXLogoutCallback;
import com.jxccp.im.chat.common.config.Server;
import com.jxccp.im.chat.common.entity.JXCustomerConfig;
import com.jxccp.im.chat.manager.JXImManager;
import com.jxccp.im.util.log.JXLog;
import com.jxccp.ui.JXUiHelper;
import com.jxccp.ui.listeners.JXLinkClickListener;
import com.jxccp.ui.utils.JXCommonUtils;
import com.jxccp.ui.utils.JXContextWrapper;
import com.jxccp.ui.utils.JXPermissionUtil;
import com.jxccp.ui.view.JXInitActivity;
import com.jxccp.ui.view.JXSettingActivity;

import java.util.Locale;


public class MainActivity extends AppCompatActivity implements JXPermissionUtil
        .OnPermissionCallback, View.OnClickListener {

    JXPermissionUtil mJXPermissionUtil;
    int permissRequestCode = 1;
    Button requestBtn;
    int lang = 5;
    Button suborgBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        requestBtn = (Button) findViewById(R.id.btn_request);
        requestBtn.setOnClickListener(this);
        findViewById(R.id.btn_logout).setOnClickListener(this);
        findViewById(R.id.setting).setOnClickListener(this);
        suborgBtn = findViewById(R.id.btn_suborg);
        suborgBtn.setOnClickListener(this);

        mJXPermissionUtil = new JXPermissionUtil();
        //演示发送图文消
//        JXCommodity commodity = new JXCommodity();
//        commodity.setTitle("商品标题");
//        commodity.setContent("商品内容");
//        commodity.setImgUrl("https://img.alicdn.com/tfs/TB1_uT8a5ERMeJjSspiXXbZLFXa-143-59.png");
//        commodity.setUrl("https://www.taobao.com");
//        JXUiHelper.getInstance().setJxCommodity(commodity);

        //设置小米推送服务
//        JXUiHelper.getInstance().setPushDevicesToken(MiPushClient.getRegId(this));

        //链接点击监听
        JXUiHelper.getInstance().addLinkClickListener(jxLinkClickListener);

        initJxConifg();
    }


    public void onClick(View view) {
        if (view.getId() == R.id.btn_request) {
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
                String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
                mJXPermissionUtil.requestPermissions(this, permissRequestCode, permissions, this);
            } else {
                startActivity(new Intent(this, JXInitActivity.class));
            }
        } else if (view.getId() == R.id.btn_logout) {
            processLogout();
        } else if (view.getId() == R.id.switchlanguage) {
            new AlertDialog.Builder(MainActivity.this).setSingleChoiceItems(R.array.language, 5,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            lang = which;
                        }
                    }).setPositiveButton("ok", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    switchLanguage(lang);
                    dialog.dismiss();
                }
            }).show();
        } else if (view.getId() == R.id.setting) {
            startActivityForResult(new Intent(this, JXSettingActivity.class), JXSettingActivity
                    .JX_CONFIG_REQUEST_CODE);
        } else if (view.getId() == R.id.btn_suborg) {
            startActivity(new Intent(this, SuborgActivity.class));
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[]
            grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        mJXPermissionUtil.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public void onGranted() {
        startActivity(new Intent(this, JXInitActivity.class));
    }

    @Override
    public void onDenied() {
        Toast.makeText(getApplicationContext(), "无法获取权限，请允许权限后重试", Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mJXPermissionUtil = null;
        JXUiHelper.getInstance().addLinkClickListener(null);
    }

    private void processLogout() {
        new Thread(new Runnable() {

            @Override
            public void run() {
                JXImManager.Config.getInstance().unRegisterPushService();
                JXImManager.Login.getInstance().logout(new JXLogoutCallback() {

                    @Override
                    public void onSuccess() {
                        runOnUiThread(new Runnable() {
                            public void run() {
                                JXUiHelper.getInstance().destroy();
                                JXCommonUtils.showToast(getApplicationContext(), "logout success!");
                            }
                        });
                    }

                    @Override
                    public void onError(int code, String reason) {
                        runOnUiThread(new Runnable() {
                            public void run() {
                                JXCommonUtils.showToast(getApplicationContext(), "logout fialed !");
                            }
                        });
                    }
                });
            }
        }).start();
    }

    @Override
    protected void onResume() {

        super.onResume();
    }

    //切换语言
    public void switchLanguage(int language) {
        // 应用用户选择语言
        switch (language) {
            case 0:
                JXUiHelper.getInstance().setLanguage(Locale.SIMPLIFIED_CHINESE);
                break;
            case 1:
                JXUiHelper.getInstance().setLanguage(new Locale("zh", "HK"));
                break;
            case 2:
                JXUiHelper.getInstance().setLanguage(Locale.ENGLISH);
                break;
        }
        Intent intent = new Intent(this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
    }

    @Override
    protected void attachBaseContext(Context newBase) {
        Locale mLocate = JXUiHelper.getInstance().getLanguge();
        Context context = JXContextWrapper.wrap(newBase, mLocate);
        super.attachBaseContext(context);
    }

    //链接点击监听
    JXLinkClickListener jxLinkClickListener = new JXLinkClickListener() {
        @Override
        public void onLinkClick(String link) {
            JXLog.d("main activity link = " + link);
            if (!link.startsWith("http://") && !link.startsWith("https://")) {
            } else {
                Uri uri = Uri.parse(link);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                intent.putExtra(Browser.EXTRA_APPLICATION_ID, getApplication().getPackageName());
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                try {
                    getApplication().startActivity(intent);
                } catch (ActivityNotFoundException e) {
                    JXLog.e("JXChatAdatper , URLSpan Actvity was not found for intent, " + intent
                            .toString(), e);
                }
            }
        }
    };

    //配置设置
    public void initJxConifg() {
        //服务器地址
        SharedPreferences sharedPreferences = this.getSharedPreferences(JXSettingActivity
                .CONFIG_NAME, this.MODE_PRIVATE);
        String protocal = TextUtils.isEmpty(sharedPreferences.getString("protocol", "")) ?
                JXImManager.Config.getInstance().getServerAddress().protocol :
                sharedPreferences.getString("protocol", "");
        String host = TextUtils.isEmpty(sharedPreferences.getString("host", "")) ?
                JXImManager.Config.getInstance().getServerAddress().ip :
                sharedPreferences.getString("host", "");
        String port = TextUtils.isEmpty(sharedPreferences.getString("port", "")) ?
                String.valueOf(JXImManager.Config.getInstance().getServerAddress().port) :
                sharedPreferences.getString("port", "");
        Server.Address address = new Server.Address();
        address.protocol = protocal;
        address.ip = host;
        address.port = Integer.parseInt(port);
        JXImManager.Config.getInstance().setServerAddress(address);

        //crm对接客户信息
        String cid = sharedPreferences.getString("cid", "");
        String name = sharedPreferences.getString("name", "");
        if (!TextUtils.isEmpty(cid) && !TextUtils.isEmpty(name)) {
            JXCustomerConfig customerConfig = new JXCustomerConfig();
            customerConfig.setCid(cid);
            customerConfig.setName(name);
            JXImManager.Config.getInstance().setCustomerConfig(customerConfig);
        }

        //设置转人工按钮可见
        boolean showRobotTransfer = sharedPreferences.getBoolean("showRobotTransfer", true);
        JXUiHelper.getInstance().setShowRobotTransferEnable(showRobotTransfer);

        //设置关闭会话按钮可见
        boolean showEndSession = sharedPreferences.getBoolean("showEndSession", true);
        JXUiHelper.getInstance().setShowEndSessionEnable(showEndSession);

        //设置消息箱按钮可见
        boolean messageboxEnable = sharedPreferences.getBoolean("messageBox", true);
        JXUiHelper.getInstance().setMsgBoxEnable(messageboxEnable);

        //设置使用常见问题（目前只在灰度上线，需要手动设置）
        boolean useCommonQuestion = sharedPreferences.getBoolean("useCommonQuestion", false);
        JXUiHelper.getInstance().setUseCommonQuestion(useCommonQuestion);


        //是否允许发图片给机器人
        boolean sendImgToRobotEnable = sharedPreferences.getBoolean("sendImgToRobot", false);
        JXUiHelper.getInstance().setSendImgToRobotEnable(sendImgToRobotEnable);

        //是否允许发语音给机器人
        boolean sendVoiceToRobotEnable = sharedPreferences.getBoolean("sendVoiceToRobot", false);
        JXUiHelper.getInstance().setSendVoiceToRobotEnable(sendVoiceToRobotEnable);

        //切换渠道号后重新请求
        boolean reRequestAfterChangeChannelNo = sharedPreferences.getBoolean("reRequest", false);
        JXUiHelper.getInstance().setReRequestAfterChangeChannel(reRequestAfterChangeChannelNo);

        boolean showSuborgBtn = sharedPreferences.getBoolean("suborg", false);
        if (showSuborgBtn) {
            suborgBtn.setVisibility(View.VISIBLE);
        } else {
            suborgBtn.setVisibility(View.GONE);
        }

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == JXSettingActivity.JX_CONFIG_REQUEST_CODE) {
            initJxConifg();
        }
    }
}
